package com.smarttest.portal.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smarttest.common.util.DateTimeUtils;
import com.smarttest.portal.mapper.ZentaobugcountMapper;
import com.smarttest.portal.pojo.Zentaobugcount;
import com.smarttest.portal.pojo.ZentaobugcountExample;
import com.smarttest.portal.pojo.ZentaobugcountExample.Criteria;
import com.smarttest.portal.refresh.onlinequery.dao.ZentaoDao;
import com.smarttest.portal.service.ZentaoService;
@Service
public class ZentaoServiceImpl implements ZentaoService {
	@Autowired
	ZentaoDao ZentaoDao;
	@Autowired
	ZentaobugcountMapper zentaobugcountMapper;
	private ScheduledExecutorService scheduledExecutorService = Executors
			.newSingleThreadScheduledExecutor();
	@Override
	public String queryBUGToday(Integer productId) {
		// TODO Auto-generated method stub
		return ZentaoDao.getBugToString(productId);

	}
	@Override
	public String getProducts() {
		// TODO Auto-generated method stub
		return ZentaoDao.getProducts();

	}
	@PostConstruct
	/**
	 * 定时从禅道数据库生成数据到本地
	 */
	public void generateTodayBugTolocal() {

		System.out.println("开始执行禅道BUG统计定时任务");
		ZentaobugcountExample example = new ZentaobugcountExample();
		example.setOrderByClause("statistictime asc");
		Criteria criteria = example.createCriteria();
		criteria.andStatistictimeEqualTo(DateTimeUtils.daysStart(-1));
		List<Zentaobugcount> l = zentaobugcountMapper.selectByExample(example);
		if (l.size() < 1) {
			ZentaoDao.getYesterdayBugTolocal();
		}
		long oneDay = 24 * 60 * 60 * 1000;
		long initDelay = getTimeMillis("00:00:01") - System.currentTimeMillis();
		initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
		scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {

			@Override
			public void run() {
				ZentaoDao.getYesterdayBugTolocal();
			}
		}, initDelay, oneDay, TimeUnit.MILLISECONDS);
	}
	/** 
	 * 获取指定时间对应的毫秒数 
	 * @param time "HH:mm:ss" 
	 * @return 
	 */  
	private static long getTimeMillis(String time) {  
	    try {  
	        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
	        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
	        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
	        return curDate.getTime();  
	    } catch (ParseException e) {  
	        e.printStackTrace();  
	    }  
	    return 0;  
	}
	@Override
	public int updateBugTolocalNow() {
		// TODO Auto-generated method stub
		return ZentaoDao.updateBugTolocalNow();
	}  
}
